<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <nav class="nav">
      <button data-path="/">index</button>
      <button data-path="/home">home</button>
      <button data-path="/about">about</button>
    </nav>
    <div class="router-view" style="height:200px; width: 200px; border:1px solid black;"></div>
  </div>
</body>
<script>
  const routes = [
    {
      path: '/',
      component: `
        <div class="index">index 页面</div>
      `
    },
    {
      path: '/home',
      component: `
        <div class="home">home 页面</div>
      `
    },
    {
      path: '/about',
      component: `
        <div class="about">about 页面</div>
      `
    },
  ]

  const routerview = document.querySelector('.router-view')
  const nav = document.querySelectorAll('.nav button')

  nav.forEach(el => el.addEventListener('click', (e) => {
    location.hash = e.target.dataset.path
  }))

  window.onload = () => {
    const path = location.hash.split('#')[1]
    metchRoute(path)
  }

  const metchRoute = (path) => {
    for (const route of routes) {
      // 找到对应key匹配的路由
      if (route.path === path) {
        // 渲染组件
        return routerview.innerHTML = route.component
      } else {
        // 找不到404
        routerview.innerHTML = '404 not found'
      }
    }
  }

  // 监听Hash值的变化
  window.onhashchange = (e) => {
    // 回去新hash地址
    const { newURL } = e
    // 截取出路由key
    const path = newURL.split('#')[1]
    // 匹配路由
    metchRoute(path)
  }

</script>

</html>